package com.xiyin.controller;


import com.xiyin.entity.UserBatch;
import com.xiyin.service.IUserBatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能点:1.批量插入
 *       2.事务管理
 *       3.自定义sql
 * @author xukaihang
 * @since 2024-08-18
 */
@RestController
@RequestMapping("/user-batch")
public class UserBatchController {
    @Autowired
    private IUserBatchService userBatchService;
    //新增
    @PostMapping("/add")
    public ResponseEntity<String> save() {
        List<UserBatch> users = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            UserBatch user = new UserBatch();
            user.setUserName("User" + i);
            user.setAge(i);
            user.setEmail("user" + i + "@example.com");
            user.setStatus("0");
            users.add(user);
        }
        //批量保存，默认1000次提交commit一次
        boolean save = userBatchService.saveBatch(users);
        return ResponseEntity.ok(save ? "批量保存成功" : "批量保存失败");
    }

    //新增数据，事务管理，如果其中有一条数据失败，则全部回滚
    @Transactional
    @PostMapping("/saveByRollback")
    public ResponseEntity<String> saveByRollback() {
        boolean save = false;
        for (int i = 0; i < 10; i++) {
            UserBatch user = new UserBatch();
            user.setUserName("User" + i);
            user.setAge(i);
            user.setEmail("user" + i + "@example.com");
            user.setStatus("0");
            if (i == 5) {
                throw new RuntimeException("测试事务回滚");
            }
            save = userBatchService.save(user);
        }
        return ResponseEntity.ok(save ? "批量保存成功" : "批量保存失败");
    }

    //自定义sql-在XML文件中编写SQL语句
    @GetMapping ("/zidingyiBySQL")
    public ResponseEntity<List<UserBatch>> zidingyiBySQL() {
        List<UserBatch> userBatches = userBatchService.zidingyiBySQL();
        return ResponseEntity.ok(userBatches);
    }

    //自定义sql-在注解中编写SQL语句
    @GetMapping ("/zidingyiByZhujie")
    public ResponseEntity<List<UserBatch>> zidingyiByZhujie() {
        List<UserBatch> userBatches = userBatchService.zidingyiByZhujie();
        return ResponseEntity.ok(userBatches);
    }

    //自定义sql-结合条件构造器使用
    @GetMapping ("/zidingyiByCondition")
    public ResponseEntity<List<UserBatch>> zidingyiByCondition() {
        List<UserBatch> userBatches = userBatchService.zidingyiByCondition();
        return ResponseEntity.ok(userBatches);
    }
}
